<template>
  <ElInput :value="label || props.modelValue" :placeholder="`请选择${column.label}`" readonly @click="onClick">
    <template #append>
      <ElButton @click="onClick">选择</ElButton>
    </template>
  </ElInput>
</template>
<script setup lang="ts">
  import { h, ref, watch } from 'vue'
  import { ElInput, ElButton } from 'element-plus'
  import { footer, popup } from "@/components/Popup"
  import { Column, ShowPosition } from '@/seed-application/types'
  import { PagePanel } from '@/components/Panel';
  import { labelApi } from '@/seed-application/utils/RelUtil';

  const props = defineProps<{
    column: Column,
    modelValue?: any,
    // label?: string,
    position?: ShowPosition
  }>()
  const emits = defineEmits(['update:modelValue'])
  const column = props.column

  const value = ref()
  const label = ref()
  let chooseLabel
  watch(() => props.modelValue, async (val) => {
    value.value = val
    if(val) label.value = await labelApi(props.column, val)
  }, { immediate: true })
  // watch(() => props.label, (val) => {
  //   label.value = val
  //   chooseLabel = val
  // }, { immediate: true })

  const onClick = () => {
    const popupProps = {title: `请选择${column.label}`, position: props.position}
    popup(popupProps, {
      default: () => h(PagePanel, {column, value: value.value, label: label.value, onChoose}),
      footer: footer(ok)
    })
  }

  const onChoose = (val, lbl) => {
    value.value = val
    chooseLabel = lbl
  }

  function ok() {
    label.value = chooseLabel
    emits('update:modelValue', value.value)
  }
</script>
